package model;

import java.util.ArrayList;
import java.util.Random;

import org.jdom.Document;
import org.jdom.Element;
import org.newdawn.slick.SlickException;

import controller.BestlistManager;

public class LevelPartialFactory
{
	private static Document doc;
	
	static
	{
		doc = BestlistManager.File2XML("data/levelpartials.xml");
	}
	
	public static LevelPartial getLevelPartial(double diff)
	{
		Object[] o_levelPartials = doc.getRootElement().getChildren().toArray();
		ArrayList<Element> levelPartials = new ArrayList<Element>();
		for (Object levelPartial:o_levelPartials)
		{
			Element e = (Element)levelPartial;
			String dmin = e.getAttributeValue("diffmin");
			String dmax = e.getAttributeValue("diffmax");
			//Double dmin = Double.parseDouble(e.getAttributeValue("diffmin"));
			//Double dmax = Double.parseDouble(e.getAttributeValue("diffmax"));
			if (dmin != null && Double.parseDouble(dmin) > diff)
			{
				continue;
			}
			if (dmax != null && Double.parseDouble(dmax) < diff)
			{
				continue;
			}
			levelPartials.add(e);
		}
		
		Element e = levelPartials.get(new Random().nextInt(levelPartials.size()));

		Object[] o_items = e.getChildren().toArray();
		LevelPartial levelPartial = new LevelPartial(Double.parseDouble(e.getAttributeValue("height")));

		for (Object o_item:o_items)
		{
			Element item = (Element)o_item;
			String type = item.getName();
			double x = Double.parseDouble(item.getAttributeValue("x"));
			double y = Double.parseDouble(item.getAttributeValue("y")) + 1;
			
			try
			{
				if (type.equals("Normal"))
				{
					levelPartial.add(new Platform(x, y));
				}
				else if (type.equals("HorizMov"))
				{
					levelPartial.add(new HorizMovPlatform(x, y));
				}
				else if (type.equals("VertMov"))
				{
					levelPartial.add(new VertMovPlatform(x, y));
				}
				else if (type.equals("Monster"))
				{
					levelPartial.add(new Monster(x, y));
				}
				else if (type.equals("Breakable"))
				{
					levelPartial.add(new BreakablePlatform(x, y));
				}
				else if (type.equals("Dissolving"))
				{
					levelPartial.add(new DissolvingPlatform(x, y));
				}
				else if (type.equals("Spring"))
				{
					levelPartial.add(new Spring(x, y));
				}
			}
			catch (SlickException ex)
			{
				ex.printStackTrace();
			}
			
		}
		
		return levelPartial;
	}
	
}
